#include "NoiseSphere.h"
#include "Ray.h"
#include <math.h>
#include "HTCalc.h"
#include <ctime>

//bool Sphere::Intersect(D3DXVECTOR3 ray)
//{
//	return false;
//}
//
//float NoiseSphere::Intersect(RAY &ray) 
//{
//	D3DXVECTOR3 dst = ray.origin - this->center;
//	float B = D3DXVec3Dot(&dst, &ray.direction);
//	float C = D3DXVec3Dot(&dst, &dst) - (this->radius );
//	float D = B*B - C;
//	float distance;
//	distance = D > 0 ? -B - sqrt(D) :  FLT_MAX;
//	if(distance >= 0 && distance != FLT_MAX)
//	{
//		int freq = 2;
//		//::srand(::time(0));
//		//float random = (::rand()%5)/5.0f;
//		D3DXVECTOR3 pointOnSphere = ray.origin + (ray.direction * distance);
//		double temp = HTCalc::Noise(pointOnSphere, freq);
//		//double multiplier = (1.0/freq)*temp;
//		//D3DXVECTOR3 dst = ray.origin - this->center;
//		float B = D3DXVec3Dot(&dst, &ray.direction);
//		float C = D3DXVec3Dot(&dst, &dst) - (this->radius - .05f);
//		float D = B*B - C;
//		return D > 0 ? -B - sqrt(D) :  FLT_MAX;
//	}
//	return FLT_MAX;
//}

float NoiseSphere::Density(D3DXVECTOR3 &point)
{
	float r1 = this->radiusInner * radiusInner;
	float r2 = radius*radius;
	float distanceFromCenter = pow((point.x - center.x),2) + pow((point.y - center.y),2) + pow((point.z - center.z),2);
	if(distanceFromCenter <= r1)
		return 1.0f;
	else if(distanceFromCenter >= r2)
		return 0.0f;
	else
		return ((.5f * (1.0f + (1.0f/4.0f)*HTCalc::Noise(4.0f*point,0.0))) * (::D3DXVec3Length(&(point - center))/(this->radius)));		//return (.2f + HTCalc::Turbulence(point, 1.0, 10.0));}

/*void NoiseSphere::Normal(D3DXVECTOR3* output, D3DXVECTOR3 &point)
{
Given 'samplepoint' with a density of 'sampledensity'

    normal.x = noise_ptr->density(
                     D3DXVECTOR3(samplepoint.x - epsilon,
                             samplepoint.y,
                             samplepoint.z)) - sampledensity;
    normal.y = noise_ptr->density(
                     Point3D(samplepoint.x,
                             samplepoint.y - epsilon,
                             samplepoint.z)) - sampledensity;
    normal.z = noise_ptr->density(
                     Point3D(samplepoint.x,
                             samplepoint.y,
                             samplepoint.z - epsilon)) - sampledensity;

    Normalize the normal vector
    normal = normal / |normal|
}*/